package jrain.fw.core.service.ctx;

import jrain.fw.core.log.Logger;
import jrain.fw.core.log.LoggerFactory;
import jrain.fw.core.service.ServiceCfg;
import jrain.fw.core.service.support.ClasspathAnnotationServiceContext;
import jrain.fw.core.utils.FwUtils;
import jrain.utils.collection.RMap;
import jrain.utils.exception.ServiceException;
import jrain.utils.lang.StringUtils;

/**
 * <pre>
 * 作者：3244924214@qq.com 
 * 描述： 容器提供者
 * </pre>
 */
public class CtxServiceProvider {

	private static volatile CtxService context = null;
	private static final Object lock = new Object();
	private static final Logger log = LoggerFactory.getLogger("service-ctx");

	public static CtxService getContext() {
		if (context == null) {
			synchronized (lock) {
				RMap<String, Object> cfg = FwUtils.getFwCfg();
				String ctxClass = StringUtils.trimNull(cfg.get(ServiceCfg.serviceCtxClass.getName()),
						ServiceCfg.serviceCtxClass.getValue());
				if (StringUtils.isEmpty(ctxClass)) {
					context = new ClasspathAnnotationServiceContext();
				} else {
					try {
						context = (CtxService) Class.forName(ctxClass).newInstance();
					} catch (Throwable t) {
						log.error(t.getMessage(), t);
						throw new ServiceException(t.getMessage(), t);
					}
				}
			}
		}
		return context;
	}

}
